package com.gjp.etfweb.business;

import com.gjp.etfweb.bean.FundInfo;
import com.gjp.etfweb.bean.FundPortfolio;
import com.gjp.etfweb.bean.FundPortfolioRoot;
import com.gjp.etfweb.common.Constant;
import com.gjp.etfweb.form.FundPortfolioRootForm;
import com.gjp.etfweb.form.QueryForm;
import com.gjp.etfweb.policys.FixedInvestmentPolicy;
import com.gjp.etfweb.utils.BeanConvertUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class FundPortfolioBusiness {
    private final CommonBusiness commonBusiness;

    public FundPortfolioBusiness(CommonBusiness commonBusiness) {
        this.commonBusiness = commonBusiness;
    }

    public FundPortfolioRoot processing(FundPortfolioRootForm form) {
        FundPortfolioRoot fundPortfolioRoot = BeanConvertUtils.convertBean(form, FundPortfolioRoot.class);
        // 计算每个基金的涨跌详情
        for (FundPortfolio fundPortfolio : fundPortfolioRoot.getFundList()) {
            // 基金占比购买金额
            BigDecimal buyAmount = fundPortfolioRoot.getInitBuyAmount().multiply(fundPortfolio.getProportion());
            // 构造查询对象
            QueryForm queryForm = new QueryForm();
            queryForm.setCode(fundPortfolio.getCode());
            queryForm.setStartTime(fundPortfolio.getStartTime());
            queryForm.setBuyAmount(buyAmount);
            queryForm.setStopPoint(BigDecimal.valueOf(100));
            queryForm.setDayInterval(fundPortfolioRoot.getDayInterval());
            queryForm.setServiceChargeRate(fundPortfolio.getServiceChargeRate());
            // 计算定投结果
            FundInfo fundInfo = commonBusiness.processing(queryForm, Constant.FILE_ROOT, new FixedInvestmentPolicy());
            fundPortfolio.setFundInfo(fundInfo);
            // 计算总投入金额
            fundPortfolioRoot.setTotalCost(fundPortfolioRoot.getTotalCost().add(fundInfo.getTotalBuyAmount()));
            // 计算总投入收益
            fundPortfolioRoot.setTotalEarnings(fundPortfolioRoot.getTotalEarnings().add(fundInfo.getEarningsAmount()));
        }

        // 计算组合
        for (FundPortfolio fundPortfolio : fundPortfolioRoot.getFundList()) {
            // 基金当前占比  成本+收益/总市值
            BigDecimal proportion = fundPortfolio.getFundInfo().getTotalBuyAmount()
                    .add(fundPortfolio.getFundInfo().getEarningsAmount())
                    .divide(fundPortfolioRoot.getTotalCost(), 4, BigDecimal.ROUND_HALF_UP);
            fundPortfolio.setProportion(proportion);

            // 计算净值历史
        }
        return fundPortfolioRoot;
    }
}
